<template>
  <div class="home-dashboard">
    <!-- 顶部状态栏 -->
    <div class="dashboard-header">
      <div class="container">
        <lay-row>
          <lay-col md="10">
            <div class="time-display">
              <div class="current-time">{{ currentTime }}</div>
              <div class="current-date">{{ currentDate }}</div>
            </div>
          </lay-col>

          <lay-col md="4">
            <div class="system-status">
              <i class="fas fa-check-circle"></i>
              <span>系统运行正常</span>
            </div>
          </lay-col>

          <lay-col md="10">
            <div class="eco-mode-toggle">
              <span>节能模式</span>
              <lay-switch v-model="ecoMode" @change="toggleEcoMode"></lay-switch>
            </div>
          </lay-col>
        </lay-row>
      </div>
    </div>

    <!-- 环境监测卡片 -->
    <div class="sensor-cards">
      <div class="container">
        <lay-row space="15">
          <lay-col md="6">
            <lay-card class="sensor-card">
              <div class="card-header">
                <h3>室内温度</h3>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
              </div>
              <div class="card-value">
                {{ temperature }}<span class="unit">°C</span>
              </div>
              <div :class="temperatureStatus.color" class="status-message">
                <i :class="temperatureStatus.icon"></i>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
                {{ temperatureStatus.text }}
              </div>
<!--              <div class="trend-indicator">-->
<!--                 <i :class="tempTrend > 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'"-->
<!--                   :style="{color: tempTrend > 0 ? '#ff5722' : '#1e9fff'}"></i>-->
<!--                <lay-icon type="layui-icon-face-smile"></lay-icon>-->
<!--                <span>{{ Math.abs(tempTrend).toFixed(1) }}°C</span>-->
<!--              </div>-->
              <div class="sensor-chart" ref="tempChart"></div>
            </lay-card>
          </lay-col>

          <!-- 其他传感器卡片 (湿度, 空气质量, CO2) -->
          <lay-col md="6">
            <lay-card class="sensor-card">
              <div class="card-header">
                <h3>室内湿度</h3>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
              </div>
              <div class="card-value">
                {{ humidity }}<span class="unit">%</span>
              </div>
              <div :class="humidityStatus.color" class="status-message">
                 <i :class="humidityStatus.icon"></i>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
                {{ humidityStatus.text }}
              </div>
              <div class="sensor-chart" ref="humidityChart"></div>
            </lay-card>
          </lay-col>

          <lay-col md="6">
            <lay-card class="sensor-card">
              <div class="card-header">
                <h3>空气质量</h3>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
              </div>
              <div class="card-value" :style="{ color: airQualityStatus.numColor }">
                {{ airQuality }}<span class="unit">AQI</span>
              </div>
              <div class="quality-bar">
                <div class="quality-fill" :class="airQualityStatus.bgColor"
                  :style="{ width: `${ Math.min((airQuality / 1300) * 100, 100)}%` }"></div>
              </div>
              <div class="quality-labels">
                <span>优</span>
                <span>良</span>
                <span>轻度</span>
                <span>中度</span>
                <span>重度</span>
                <span>严重</span>
              </div>
              <div :class="airQualityStatus.textColor" class="status-message">
                <i :class="airQualityStatus.icon"></i> {{ airQualityStatus.text }}
              </div>
            </lay-card>
          </lay-col>

          <lay-col md="6">
            <lay-card class="sensor-card">
              <div class="card-header">
                <h3>CO₂ 浓度</h3>
                <lay-icon type="layui-icon-face-smile"></lay-icon>
              </div>
              <div class="card-value">
                {{ co2Level }}<span class="unit">ppm</span>
              </div>
              <div class="quality-bar">
                <div class="quality-fill" :class="co2Status.bgColor"
                  :style="{ width: `${Math.min(co2Level / 20, 100)}%` }"></div>
              </div>
              <div class="co2-labels">
                <span>400</span>
                <span>800</span>
                <span>1200</span>
                <span>1600</span>
                <span>2000</span>
              </div>
              <div :class="co2Status.textColor" class="status-message">
                <i :class="co2Status.icon"></i> {{ co2Status.text }}
              </div>
            </lay-card>
          </lay-col>
        </lay-row>
      </div>
    </div>

    <!-- 设备控制区域 -->
    <div class="device-controls">
      <div class="container">
        <h2>设备控制</h2>
        <lay-row space="15">
          <!-- 空调控制 -->
          <lay-col md="8">
            <lay-card class="device-card">
              <div class="device-header">
                <i class="fas fa-snowflake"></i>
                <h3>空调控制</h3>
                <lay-switch v-model="acOn" @change="toggleAC"></lay-switch>
              </div>

              <div class="control-section">
                <div class="control-label">温度设置 <span class="value">{{ acTemperature }}°C</span></div>
                <lay-slider v-model="acTemperature" :min="16" :max="30" :disabled="!acOn"></lay-slider>
                <div class="slider-labels">
                  <span>16°C</span>
                  <span>30°C</span>
                </div>
              </div>

              <div class="control-section">
                <div class="control-label">模式选择</div>
                <div class="mode-buttons">
                  <lay-button v-for="mode in acModes" :key="mode.value"
                    :type="acMode === mode.value ? 'primary' : 'default'" @click="acMode = mode.value"
                    :disabled="!acOn">
                    <i :class="mode.icon" class="fa-fw"></i> {{ mode.label }}
                  </lay-button>
                </div>
              </div>
            </lay-card>
          </lay-col>

          <!-- 风扇控制 -->
          <lay-col md="8">
            <lay-card class="device-card">
              <div class="device-header">
                <i class="fas fa-fan"></i>
                <h3>风扇控制</h3>
                <lay-switch v-model="fanOn" @change="toggleFan"></lay-switch>
              </div>

              <div class="control-section">
                <div class="control-label">风速调节 <span class="value">{{ fanSpeedLabels[fanSpeed] }}</span></div>
                <lay-slider v-model="fanSpeed" :min="1" :max="5" :step="1" :disabled="!fanOn"></lay-slider>
                <div class="slider-labels">
                  <span>低速</span>
                  <span>高速</span>
                </div>
              </div>

              <div class="control-section">
                <div class="control-label">摆头控制 <span class="value">{{ fanSwing ? '开启' : '关闭' }}</span></div>
                <lay-button :type="fanSwing ? 'primary' : 'default'" @click="fanSwing = !fanSwing" :disabled="!fanOn">
                  <i class="fas fa-sync-alt" :class="{ 'fa-spin': fanSwing && fanOn }"></i>
                  {{ fanSwing ? '摆头已开启' : '摆头已关闭' }}
                </lay-button>
              </div>
            </lay-card>
          </lay-col>

          <!-- 照明控制 -->
          <lay-col md="8">
            <lay-card class="device-card">
              <div class="device-header">
                <i class="fas fa-lightbulb"></i>
                <h3>智能照明</h3>
                <lay-switch v-model="lightOn" @change="toggleLight"></lay-switch>
              </div>

              <div class="control-section">
                <div class="control-label">亮度调节 <span class="value">{{ lightBrightness }}%</span></div>
                <lay-slider v-model="lightBrightness" :min="10" :max="100" :disabled="!lightOn"></lay-slider>
                <div class="slider-labels">
                  <span>暗</span>
                  <span>亮</span>
                </div>
              </div>

              <div class="control-section">
                <div class="control-label">灯光模式</div>
                <div class="light-mode-grid">
                  <lay-button v-for="mode in lightModes" :key="mode.value"
                    :type="lightMode === mode.value ? 'primary' : 'default'" @click="lightMode = mode.value"
                    :disabled="!lightOn">
                    {{ mode.label }}
                  </lay-button>
                </div>
              </div>
            </lay-card>
          </lay-col>
        </lay-row>
      </div>
    </div>

    <!-- 数据分析区域 -->
    <div class="data-analysis">
      <div class="container">
        <h2>数据分析</h2>
        <lay-card>
          <div class="chart-controls">
            <lay-radio-group v-model="selectedMetric" size="md" type="button">
              <lay-radio value="temperature">温度</lay-radio>
              <lay-radio value="humidity">湿度</lay-radio>
              <lay-radio value="airQuality">空气质量</lay-radio>
              <lay-radio value="co2">CO₂浓度</lay-radio>
            </lay-radio-group>

            <lay-radio-group v-model="selectedTimeRange" size="md" type="button">
              <lay-radio value="day">今日</lay-radio>
              <lay-radio value="week">本周</lay-radio>
              <lay-radio value="month">本月</lay-radio>
              <lay-radio value="year">全年</lay-radio>
            </lay-radio-group>
          </div>

          <div class="main-chart" ref="mainChart"></div>
        </lay-card>
      </div>
    </div>

    <!-- 设备状态概览 -->
    <div class="device-overview">
      <div class="container">
        <h2>设备状态概览</h2>
        <lay-row space="15">
          <lay-col v-for="device in devices" :key="device.id" md="6">
            <lay-card hoverable>
              <div class="device-items">
                <div style="flex: 2;">
                  <div class="device-icon" :style="{ backgroundColor: device.bgColor }">
                    <lay-icon :type="device.icon"></lay-icon>
                  </div>
                </div>
                <div style="flex:8">
                  <div class="device-info">
                    <div class="device-name">{{ device.name }}</div>
                    <div class="device-status" :class="device.status === '在线' ? 'online' : 'offline'">
                      {{ device.statusStr }}
                    </div>
                  </div>
                </div>
                <div style="flex:1">
                  <lay-icon></lay-icon>
                </div>
              </div>
            </lay-card>
          </lay-col>
        </lay-row>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, watch } from 'vue';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import {
  getAllDeviceOverviewApi,
  getMessageHourApi,
  getMessagePageApi,
  sendEnergyModeApi,
  sendMessageApi
} from "~/api/system/message";
import {
  AcControlCommand,
  MonitorData,
  YearMonthWeekDayData,
  AcMode,
  FanControlCommand,
  LightControlCommand, DeviceOverview, DataAnalysis
} from "~/types/system/mseeage";

export default defineComponent({
  name: 'HomeDashboard',

  setup() {
    // 响应式数据
    const currentTime = ref('');
    const currentDate = ref('');

    // 系统状态
    const ecoMode = ref(false);

    const monitorData = {} as MonitorData;
    const yearMonthWeekDayData = {} as YearMonthWeekDayData;
    const dataAnalysis = {} as DataAnalysis;
    // 监控数据
    const temperature = ref(30.2);
    const tempTrend = ref(-20.8);
    const humidity = ref(80);
    const airQuality = ref(75);
    const co2Level = ref(650);

    // 图表元素引用
    const tempChart = ref<HTMLElement | null>(null);
    const humidityChart = ref<HTMLElement | null>(null);
    const mainChart = ref<HTMLElement | null>(null);

    // 设备控制
    // 空调
    const acOn = ref(true);
    const acTemperature = ref(25);
    const acMode = ref<AcMode>('COOL');
    const acModes = ref([
      { label: '制冷', value: 'COOL', icon: 'fas fa-snowflake' },
      { label: '制热', value: 'HEAT', icon: 'fas fa-fire' },
      { label: '除湿', value: 'DRY', icon: 'fas fa-tint-slash' },
      { label: '自动', value: 'FAN', icon: 'fas fa-magic' }
    ]);
    const acControlCommand = {} as AcControlCommand;
    const fanControlCommand = {} as FanControlCommand;
    const lightControlCommand = {} as LightControlCommand;

    // 风扇
    const fanOn = ref(false);
    const fanSpeed = ref(3);
    const fanSpeedLabels: Record<number, string> = {
      1: '一档',
      2: '二档',
      3: '三档',
      4: '四档',
      5: '五档'
    };
    const fanSwing = ref(true);

    // 照明
    const lightOn = ref(true);
    const lightBrightness = ref(80);
    const lightMode = ref('normal');
    const lightModes = ref([
      { label: '正常', value: 'normal' },
      { label: '阅读', value: 'reading' },
      { label: '影院', value: 'movie' },
      { label: '夜灯', value: 'night' },
      { label: '自动', value: 'auto' },
      { label: '自定义', value: 'custom' }
    ]);

    // 数据分析
    const selectedMetric = ref('temperature');
    const metrics = ref([
      { label: '温度', value: 'temperature' },
      { label: '湿度', value: 'humidity' },
      { label: '空气质量', value: 'airQuality' },
      { label: 'CO₂浓度', value: 'co2' }
    ]);
    const selectedTimeRange = ref('day');
    const timeRanges = ref([
      { label: '今日', value: 'day' },
      { label: '本周', value: 'week' },
      { label: '本月', value: 'month' },
      { label: '全年', value: 'year' }
    ]);

    // 设备列表
    const devices = ref();

    // 计算温度属性
    const temperatureStatus = computed(() => {
      if (temperature.value > 28) {
        return {
          text: '温度过高，建议降温',
          color: 'status-warning',
          icon: 'fas fa-exclamation-triangle'
        };
      } else if (temperature.value < 20) {
        return {
          text: '温度过低，建议升温',
          color: 'status-warning',
          icon: 'fas fa-exclamation-triangle'
        };
      } else {
        return {
          text: '温度适宜',
          color: 'status-success',
          icon: 'fas fa-check-circle'
        };
      }
    });

    // 计算属性
    const humidityStatus = computed(() => {
      if (humidity.value < 30) {
        return {
          text: '湿度过低，建议加湿',
          color: 'status-warning',
          icon: 'fas fa-exclamation-triangle'
        };
      } else if (humidity.value > 70) {
        return {
          text: '湿度过高，建议除湿',
          color: 'status-warning',
          icon: 'fas fa-exclamation-triangle'
        };
      } else {
        return {
          text: '湿度适宜',
          color: 'status-success',
          icon: 'fas fa-check-circle'
        };
      }
    });

    const airQualityStatus = computed(() => {
      if (airQuality.value <= 200) {
        return {
          text: '空气优',
          textColor: 'status-success',
          numColor: '#5FB878',
          bgColor: 'quality-good',
          icon: 'fas fa-smile'
        };
      } else if (airQuality.value <= 250) {
        return {
          text: '空气良好',
          textColor: 'status-success',
          numColor: '#ecc602',
          bgColor: 'quality-good',
          icon: 'fas fa-smile'
        };
      } else if (airQuality.value <= 300) {
        return {
          text: '轻度污染',
          textColor: 'status-warning',
          numColor: '#ff8d67',
          bgColor: 'quality-moderate',
          icon: 'fas fa-exclamation-triangle'
        };
      } else if (airQuality.value <= 350) {
        return {
          text: '中度污染',
          textColor: 'status-warning',
          numColor: '#f60000',
          bgColor: 'quality-moderate',
          icon: 'fas fa-exclamation-triangle'
        };
      } else if (airQuality.value <= 400) {
        return {
          text: '重度污染',
          textColor: 'status-warning',
          numColor: '#9502f6',
          bgColor: 'quality-moderate',
          icon: 'fas fa-exclamation-triangle'
        };
      }
      else {
        return {
          text: '严重',
          textColor: 'status-danger',
          numColor: '#fb01f7',
          bgColor: 'quality-poor',
          icon: 'fas fa-exclamation-triangle'
        };
      }
    });

    const co2Status = computed(() => {
      if (co2Level.value < 800) {
        return {
          text: '浓度正常',
          textColor: 'status-success',
          bgColor: 'quality-good',
          icon: 'fas fa-check-circle'
        };
      } else if (co2Level.value < 1200) {
        return {
          text: '浓度适中',
          textColor: 'status-success',
          bgColor: 'quality-good',
          icon: 'layui-icon-face-smile'
        };
      } else {
        return {
          text: '浓度过高，请通风',
          textColor: 'status-danger',
          bgColor: 'quality-poor',
          icon: 'fas fa-exclamation-triangle'
        };
      }
    });

    // 图表实例
    let tempChartInstance: ECharts | null = null;
    let humidityChartInstance: ECharts | null = null;
    let mainChartInstance: ECharts | null = null;

    // 方法
    const updateDateTime = () => {
      const now = new Date();

      // 格式化时间
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      currentTime.value = `${hours}:${minutes}`;

      // 格式化日期
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      currentDate.value = `${year}-${month}-${day}`;
    };

    const toggleEcoMode = () => {
      if (!ecoMode.value) {
        // 启用节能模式
        sendEnergyModeApi()
      }
    };

    const toggleAC = () => {
      // 这里可以添加实际的空调控制逻辑 !acOn.value 开启 true 关闭 false
      // 设置当前空调状态
      acControlCommand.id = 1
      acControlCommand.timestamp =  new Date()
      acControlCommand.power = !acOn.value
      acControlCommand.temperature = acTemperature.value
      acControlCommand.mode = acMode.value
      acControlCommand.deviceType = 'AIR_CONDITIONER'
      sendMessageApi(acControlCommand)
    };

    const toggleFan = () => {
      // 这里可以添加实际的风扇控制逻辑 !fanOn.value 开启 true 关闭 false
      fanControlCommand.id = 2
      fanControlCommand.timestamp =  new Date()
      fanControlCommand.power = !fanOn.value
      fanControlCommand.deviceType = 'FAN'
      fanControlCommand.speed = fanSpeed.value
      fanControlCommand.oscillate = fanSwing.value
      sendMessageApi(fanControlCommand)
    };

    const toggleLight = () => {
      // 这里可以添加实际的照明控制逻辑 !lightOn.value
      lightControlCommand.id = 3
      lightControlCommand.timestamp =  new Date()
      lightControlCommand.power = !fanOn.value
      lightControlCommand.deviceType = 'LIGHT'
      lightControlCommand.brightness = lightBrightness.value;
      lightControlCommand.color = lightMode.value;
      sendMessageApi(lightControlCommand)
    };

    // 更新实时监控数据
    const updateMonitorData = () => {
      // 获取温湿度 数据
      getMessagePageApi().then(res => {
        Object.assign(monitorData, res.data);
        // 更新实时温度
        temperature.value = parseFloat(monitorData.temperature.toFixed(1));
        // 更新温度图表
          if (tempChart.value) {
            tempChartInstance = echarts.init(tempChart.value);
            const option = {
              grid: { top: 0, right: 0, bottom: 0, left: 0 },
              xAxis: { show: false, data: ['', '', '', '', '', ''] },
              yAxis: { show: false, min: 10, max: 60 },
              series: [{
                type: 'line',
                data: monitorData.temperatureList,
                smooth: true,
                symbol: 'none',
                lineStyle: { color: '#1e9fff', width: 2 },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(30, 159, 255, 0.3)' },
                    { offset: 1, color: 'rgba(30, 159, 255, 0)' }
                  ])
                }
              }]
            };
            tempChartInstance.setOption(option);
          }
        // 更新湿度
        humidity.value = parseFloat(monitorData.humidity.toFixed(1));
        // 更新湿度图表
          if (humidityChart.value) {
            humidityChartInstance = echarts.init(humidityChart.value);
            const option = {
              grid: { top: 0, right: 0, bottom: 0, left: 0 },
              xAxis: { show: false, data: ['', '', '', '', '', ''] },
              yAxis: { show: false, min: 0, max: 100 },
              series: [{
                type: 'line',
                data: monitorData.humidityList,
                smooth: true,
                symbol: 'none',
                lineStyle: { color: '#5FB878', width: 2 },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: 'rgba(95, 184, 120, 0.3)' },
                    { offset: 1, color: 'rgba(95, 184, 120, 0)' }
                  ])
                }
              }]
            };
            humidityChartInstance.setOption(option);
          }
          // 更新空气质量
          airQuality.value = parseFloat(monitorData.airQuality.toFixed(1));
          // 更新CO2
          co2Level.value = parseFloat(monitorData.co2Level.toFixed(1));
          if (mainChart.value) {
            mainChartInstance = echarts.init(mainChart.value);
            updateMainChart("temperature","day");

            // 响应窗口调整事件
            window.addEventListener('resize', () => {
              mainChartInstance?.resize();
            });
          }
      });
      // 更新设备在线列表
      getAllDeviceOverviewApi().then(res => {
        devices.value= res.data as DeviceOverview[];
      });
    };





    const updateMainChart = (selectedMetric: string, selectedTimeRange: string) => {
      // 获取 指标数据 分别为年 月 周 日   温度 湿度  pm2.5  co2
      dataAnalysis.dataType = selectedMetric;
      dataAnalysis.timeType = selectedTimeRange;
      getMessageHourApi(dataAnalysis).then((res) => {
        Object.assign(yearMonthWeekDayData, res.data);


        let xData: string[] = [];
        let seriesData: number[] = [];
        let title = '';
        let color = '#1e9fff';

        // 根据选择的指标和时间范围生成数据
        const now = new Date();
        xData = Array.from({ length: 5 }, (_, i) => {
          const hour = (now.getHours() - 5 + i) % 24;
          return `${hour.toString().padStart(2, '0')}:00`;
        });
        switch (selectedMetric) {
          case 'temperature':
            title = '温度 (°C)';
            color = '#1e9fff';
            if (selectedTimeRange=== 'day') {
              xData = xData;
              seriesData = yearMonthWeekDayData.temperatureDay;
            } else if (selectedTimeRange === 'week') {
              xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              seriesData = yearMonthWeekDayData.temperatureWeek;
            }else if (selectedTimeRange === 'month') {
              xData = ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
              seriesData = yearMonthWeekDayData.temperatureMonth;
            }else{
              xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
              seriesData = yearMonthWeekDayData.temperatureYear;
            }
            break;
          case 'humidity':
            title = '湿度 (%)';
            color = '#5FB878';
            if (selectedTimeRange === 'day') {
              xData = xData;
              seriesData = yearMonthWeekDayData.humidityDay;
            }  else if (selectedTimeRange === 'week') {
              xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              seriesData = yearMonthWeekDayData.humidityWeek;
            }else if (selectedTimeRange === 'month') {
              xData = ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
              seriesData = yearMonthWeekDayData.humidityMonth;
            }else{
              xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
              seriesData = yearMonthWeekDayData.humidityYear;
            }
            break;

          case 'airQuality':
            title = '空气质量指数 (AQI)';
            color = '#FFB800';
            if (selectedTimeRange === 'day') {
              xData = xData;
              seriesData = yearMonthWeekDayData.airQualityDay;
            }  else if (selectedTimeRange === 'week') {
              xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              seriesData = yearMonthWeekDayData.airQualityWeek;
            }else if (selectedTimeRange === 'month') {
              xData = ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
              seriesData = yearMonthWeekDayData.airQualityMonth;
            }else{
              xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
              seriesData = yearMonthWeekDayData.airQualityYear;
            }
            break;

          case 'co2':
            title = 'CO₂浓度 (ppm)';
            color = '#FF5722';
            if (selectedTimeRange === 'day') {
              xData = xData;
              seriesData = yearMonthWeekDayData.co2LevelDay;
            }  else if (selectedTimeRange === 'week') {
              xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              seriesData = yearMonthWeekDayData.co2LevelWeek;
            }else if (selectedTimeRange === 'month') {
              xData = ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日']
              seriesData = yearMonthWeekDayData.co2LevelMonth;
            }else{
              xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
              seriesData = yearMonthWeekDayData.co2LevelYear;
            }
            break;
        }
        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>{a}: {c}'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: xData,
            axisLine: {
              lineStyle: {
                color: '#d2d6de'
              }
            },
            axisLabel: {
              color: '#666'
            }
          },
          yAxis: {
            type: 'value',
            name: title,
            nameTextStyle: {
              color: '#666'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#d2d6de'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0'
              }
            },
            axisLabel: {
              color: '#666'
            }
          },
          series: [{
            name: title,
            type: 'line',
            smooth: true,
            data: seriesData,
            lineStyle: {
              color: color,
              width: 3
            },
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: color
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: `${color}33` },
                { offset: 1, color: `${color}00` }
              ])
            }
          }]
        };
        if (!mainChartInstance) return;
        mainChartInstance.setOption(option);
      });

    };

    // 生命周期钩子
    onMounted(() => {
      // 初始化时间和日期
      updateDateTime();

      // // 设置定时器，每分钟更新一次时间
      // setInterval(updateDateTime, 60000);
      // // 设置定时器，每五秒更新一次图表数据
      // setInterval(updateMonitorData, 5000);
      // 初始化图表
      updateMonitorData();
    });

    // 监听数据变化更新图表
    watch([selectedMetric, selectedTimeRange], () => {
      updateMainChart(selectedMetric.value, selectedTimeRange.value);
    });

    // 监听空调数据变动
    watch([acTemperature,acMode], () => {
      toggleAC();
    });
    // 监听风扇数据变动
    watch([fanSpeed,fanSwing], () => {
      toggleFan();
    });
    //监听灯光数据变动
    watch([lightBrightness,lightMode], () => {
      toggleLight();
    });

    // 返回数据和方法
    return {
      // 数据
      currentTime,
      currentDate,
      ecoMode,
      temperature,
      tempTrend,
      humidity,
      airQuality,
      co2Level,
      acOn,
      acTemperature,
      acMode,
      acModes,
      fanOn,
      fanSpeed,
      fanSpeedLabels,
      fanSwing,
      lightOn,
      lightBrightness,
      lightMode,
      lightModes,
      selectedMetric,
      metrics,
      selectedTimeRange,
      timeRanges,
      devices,
      humidityStatus,
      airQualityStatus,
      co2Status,
      tempChart,
      humidityChart,
      mainChart,
      temperatureStatus,

      // 方法
      toggleEcoMode,
      toggleAC,
      toggleFan,
      toggleLight
    };
  }
});
</script>

<style scoped>
.home-dashboard {
  background-color: #f2f3f5;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

/* 顶部状态栏 */
.dashboard-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 15px 0;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.time-display {
  display: flex;
  flex-direction: column;
  padding: 0 15px;
}

.current-time {
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.current-date {
  font-size: 14px;
  color: #666;
}

.system-status {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #e6f7ff;
  border-radius: 20px;
  padding: 5px 15px;
  color: #1e9fff;
}

.system-status i {
  margin-right: 5px;
  color: #52c41a;
}

.eco-mode-toggle {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 15px;
}

.eco-mode-toggle span {
  margin-right: 10px;
  color: #666;
}

/* 传感器卡片 */
.sensor-cards {
  padding: 20px 0;
}

.sensor-card {
  height: 200px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.card-header i {
  font-size: 20px;
  color: #1e9fff;
}

.card-value {
  font-size: 32px;
  font-weight: 700;
  color: #1e9fff;
  margin-bottom: 5px;
}

.unit {
  font-size: 16px;
  font-weight: normal;
  margin-left: 2px;
}

.trend-indicator {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.trend-indicator i {
  margin-right: 5px;
}

.status-warning {
  color: #FFB800;
}

.status-success {
  color: #5FB878;
}

.status-danger {
  color: #FF5722;
}

.status-message {
  font-size: 14px;
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.status-message i {
  margin-right: 5px;
}

.quality-bar {
  height: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
  margin: 10px 0;
}

.quality-fill {
  height: 100%;
  border-radius: 4px;
}

.quality-good {
  background-color: #5FB878;
}

.quality-moderate {
  background-color: #FFB800;
}

.quality-poor {
  background-color: #FF5722;
}

.quality-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.co2-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.sensor-chart {
  height: 60px;
  width: 100%;
  margin-top: 15px;
}

/* 设备控制卡片 */
.device-controls {
  padding: 20px 0;
}

.device-controls h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.device-card {
  height: 300px;
}

.device-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.device-header i {
  font-size: 20px;
  color: #1e9fff;
  margin-right: 10px;
}

.device-header h3 {
  font-size: 16px;
  font-weight: 600;
  flex: 1;
  margin: 0;
}

.control-section {
  margin-bottom: 20px;
}

.control-label {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.control-label .value {
  font-weight: 600;
  color: #333;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.mode-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.light-mode-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

/* 数据分析 */
.data-analysis {
  padding: 20px 0;
}

.data-analysis h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.chart-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.main-chart {
  height: 350px;
  width: 100%;
}

/* 设备概览 */
.device-overview {
  padding: 20px 0;
}

.device-overview h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}



.device-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  flex-shrink: 0;
}

.device-info {
  margin-left: 15px;
  flex: 1;
}

.device-name {
  font-weight: 600;
  font-size: 14px;
  color: #333;
  margin-bottom: 3px;
}

.device-status {
  font-size: 13px;
}

.online {
  color: #5FB878;
}

.offline {
  color: #909399;
}

.device-arrow {
  color: #d2d6de;
  font-size: 14px;
  margin-left: 10px;
}

/* 响应式调整 */
@media (max-width: 1268px) {

  .layui-col-md3,
  .layui-col-md4 {
    width: 100%;
    margin-bottom: 15px;
  }

  .time-display,
  .system-status,
  .eco-mode-toggle {
    justify-content: center;
    margin-bottom: 10px;
  }

  .chart-controls {
    flex-direction: column;
    gap: 10px;
  }

  .sensor-cards,
  .device-controls,
  .data-analysis,
  .device-overview {
    padding: 10px 0;
  }

  .sensor-card {
    margin-bottom: 15px;
  }
}

.device-items {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between
}
.time-display {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 15px;
  font-size: 16px;
}

.current-time {
  font-weight: bold;
  font-size: 20px;
}

.current-weather {
  margin-top: 8px;
  display: flex;
  align-items: center;
  color: #333;
}

.current-weather i {
  margin-right: 5px;
}
.custom-sun-icon {
  display: inline-block;
  width: 22px;
  height: 22px;
  background-image: url('img/a.png'); /* 替换为你的图标路径 */
  background-size: cover;
  color: transparent; /* 隐藏原图标颜色 */
}

.custom-lei-icon {
  display: inline-block;
  width: 22px;
  height: 22px;
  background-image: url('img/b.png'); /* 替换为你的图标路径 */
  background-size: cover;
  color: transparent; /* 隐藏原图标颜色 */
}
.custom-yun-icon {
  display: inline-block;
  width: 22px;
  height: 22px;
  background-image: url('img/c.png'); /* 替换为你的图标路径 */
  background-size: cover;
  color: transparent; /* 隐藏原图标颜色 */
}
</style>
